<template>
  <div>
    <el-form :model="value" :rules="rules" ref="productInfoForm"  label-width="100px" size="mini">
      <el-row :gutter="24">
          <el-col :span="11">
              <el-form-item label="商品名称：" prop="name">
                  <el-input v-model="value.name"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="11">
              <el-form-item label="助记码：" prop="productHelpCode">
                  <el-input v-model="value.productHelpCode"></el-input>
              </el-form-item>
          </el-col>
      </el-row>

        <el-row :gutter="24">
            <el-col :span="11">
                <el-form-item label="国际码：" prop="productSn">
                    <el-input v-model="value.productSn"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="自编码：" prop="name">
                    <el-input v-model="value.shopProductCode"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="11">
                <el-form-item label="进价：" prop="price">
                    <el-input-number v-model="value.price"  :precision="2" :min="0" :max="999999" >
                    </el-input-number>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="售价：" prop="originalPrice">
                    <el-input-number :precision="2" v-model="value.originalPrice" :min="0" :max="999999" >
                    </el-input-number>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="11">
                <el-form-item label="折扣：">
                    <el-input-number v-enter-number :precision="2" v-model="value.shopProductDiscount" >
                    </el-input-number>
                </el-form-item>
            </el-col>

            <el-col :span="11">
                <el-form-item label="促销价：">
                    <el-input-number v-enter-number :precision="2" v-model="value.promotionPrice" >
                    </el-input-number>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
                <el-form-item label="商品分类：" prop="productCategoryId">
                    <el-cascader
                            change-on-select
                            v-model="selectProductCateValue"
                            :options="productCateOptions">
                    </el-cascader>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="计量单位：">
                    <el-select
                            v-model="value.unit"
                            placeholder="请选择计量单位">
                        <el-option
                                v-for="item in unitOptions"
                                :key="item.id"
                                :label="item.id"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

<!--      <el-form-item label="商品图片：" prop="pic">-->
<!--        <single-upload v-model="value.pic"-->
<!--              style="width: 300px;display: inline-block;margin-left: 10px"></single-upload>-->
<!--      </el-form-item>-->

        <el-row>
            <el-col :span="11">
                <el-form-item label="商品库存：">
                    <el-input-number v-enter-number
                                     v-model="value.stock" >
                    </el-input-number>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="库存预警：">
                    <el-input-number  v-enter-number
                                      v-model="value.lowStock" >
                    </el-input-number>
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item>
            <el-radio-group v-model="value.booleanJifen">
                <el-radio :label="0">不参与积分</el-radio>
                <el-radio :label="1">参与积分</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item label="保质期：">
            <el-input-number v-enter-number
                             v-model="value.shopShelfLife">
            </el-input-number> /月
        </el-form-item>

        <el-form-item>
            <el-radio-group v-model="value.booleanManageKucun">
                <el-radio :label="0">不库管</el-radio>
                <el-radio :label="1">管库但不允许负库存</el-radio>
                <el-radio :label="2">管库但允许负库存</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-row :gutter="24">
            <el-col :span="11">
                <el-form-item label="规格：">
                    <el-input v-model="value.shopSize"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="标签：">
                    <el-input v-model="value.shopProductLabel"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

       <el-form-item label="商品特性：">
          <el-select  @change="attrChange" v-model="value.shopProductAttributeid" placeholder="请选择">
              <el-option
                v-for="item in shopProductAttributes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
          </el-select>
      </el-form-item>
     
      <el-form-item label="备注：">
        <el-input v-model="value.shopRemark"></el-input>
      </el-form-item>

        <el-form-item label="一品多码:">
            <el-col>
                <el-button @click="addPmsProductCode">添加</el-button>
            </el-col>
            <el-col v-for="(code, index) in value.pmsProductCodes" :key="index">
                <el-row :gutter="24">
                    <el-col :span="10">
                        <el-form-item label="规格:" >
                            <el-input  v-model="code.bigsize"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item  label="单位:">
                            <el-input v-model="code.smallsize"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="10">
                        <el-form-item label="数量:" >
                            <el-input  v-model="code.productnum"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item  label="单价:">
                            <el-input v-model="code.productprices"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="10">
                        <el-form-item label="产品码:" >
                            <el-input  v-model="code.productBigSn"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item >
                            <el-button @click="removePmsProductCode(index)">删除</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="title">商品子码</div>
            </el-col>
        </el-form-item>

      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleFinishCommit">完成，提交商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {fetchListWithChildren} from '@/api/productCate'
  import {fetchAreaListWithChildren,getArea} from '@/api/area'
  import SingleUpload from '@/components/Upload/singleUpload'
  import {fetchList as fetchBrandList} from '@/api/brand'
  import {fetchList as fetchFeightTemplateList} from '@/api/pms/feightTemplate';
  import {fetchAllList as fetchAttrList} from '@/api/productAttrCate'
  import {getProduct} from '@/api/product';
  import cnchar from 'cnchar';

  export default {
    name: "ProductInfoDetail",
    components: {SingleUpload},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        shopProductAttributes:[],
        hasEditCreated:false,
        isJifen: false,

        //选中商品分类的值
        selectProductCateValue: [],
        productCateOptions: [],
        //选中商品分类的值
        selectAreaValue: [],
        areaOptions: [],
        brandOptions: [],
        feightTemplateOptions:[],
        unitOptions:[{
          id: "个",
          name: "个",
        },
          {
            id: "箱",
            name: "箱",
          },
          {
            id: "条",
            name: "条",
          },

          {
            id: "盒",
            name: "盒",
          },{
            id: "包",
            name: "包",
          },{
            id: "斤",
            name: "斤",
          },{
            id: "两",
            name: "两",
          },{
            id: "件",
            name: "件",
          },{
            id: "瓶",
            name: "瓶",
          },{
            id: "千克",
            name: "千克",
          }],
        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur'}
          ],
            productSn: [
                {required: true, message: '请输入商品国际码', trigger: 'blur'},
                {min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur'}
            ],
            price: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],
            originalPrice: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],

            subTitle: [{required: true, message: '请输入商品副标题', trigger: 'blur'}],
          productCategoryId: [{required: true, message: '请选择商品分类', trigger: 'blur'}],

          brandId: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],
          description: [{required: true, message: '请输入商品介绍', trigger: 'blur'}],
          requiredProp: [{required: true, message: '该项为必填项', trigger: 'blur'}]
        }
      };
    },
    created() {
      this.getProductCateList();
      this.getAreaList();
      this.getBrandList();
      this.getFeightTemplateList();
      this.getProductAttributesList();
    },
    mounted() {
      console.log(JSON.stringify(this.value))
    },
    computed:{
      //商品的编号
      productId(){
        return this.value.id;
      }
    },
    watch: {
      'value.name' : {
        handler(newValue, oldValue){
          this.value.productHelpCode = cnchar.spell(newValue, 'first')
        },
        deep: true,
        immediate: true
      },
      productId:function(newValue){
        if(!this.isEdit)return;
        if(this.hasEditCreated)return;
        console.log(newValue)
        if(newValue===undefined||newValue==null||newValue===0)return;
        this.handleEditCreated();
      },
      selectProductCateValue: function (newValue) {
        console.log(newValue)
        if (newValue != null) {
          this.value.productCategoryId = newValue[newValue.length-1 >0?newValue.length-1:0];
          this.value.productCategoryName= this.getCateNameById(this.value.productCategoryId);
        } else {
          this.value.productCategoryId = null;
          this.value.productCategoryName=null;
        }
      },
      selectAreaValue: function (newValue) {
        console.log(newValue)
        if (newValue != null) {
          this.value.areaId = newValue[newValue.length-1 >0?newValue.length-1:0];
          this.value.areaName= this.getAreaById(this.value.areaId);
        } else {
          this.value.areaId = null;
          this.value.areaName=null;
        }
      }
    },
    methods: {
      getProductAttributesList(){
        let _this = this;
        fetchAttrList().then(response => {
          _this.shopProductAttributes = [];
          let attrs = response.data;
          for (let i = 0; i < attrs.length; i++) {
            _this.shopProductAttributes.push({id: attrs[i].id, name: attrs[i].name});
          }
        });
      },
      attrChange(v){
           for(let item of this.shopProductAttributes){
            if(v==item.id){
              this.value.shopProductAttributeName=item.name;
              break;
            }
          }
      },
      //处理编辑逻辑
      handleEditCreated(){
        if(this.value.productCategoryId!=null){

          this.selectProductCateValue.push(this.value.cateParentId);
          this.selectProductCateValue.push(this.value.productCategoryId);
        }
        if(this.value.areaId!=null){
          console.log(this.value.areaId)
          this.selectAreaValue.push(this.value.areaId);
          getArea(this.value.areaId).then(response => {
            this.selectAreaValue.push(response.data.pid);
          });
        }
        this.hasEditCreated=true;
      },
      handleFinishCommit(){
        this.$emit('finishCommit',this.isEdit);
      },
      getAreaList() {
        fetchAreaListWithChildren().then(response => {
          let list = response.data;
          this.areaOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.areaOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
      },
      getProductCateList() {
        fetchListWithChildren().then(response => {
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
      },
      getFeightTemplateList() {
        fetchFeightTemplateList({pageNum: 1, pageSize: 100}).then(response => {
                  this.feightTemplateOptions = [];
                  let feightTemplateList = response.data.records;
                  for (let i = 0; i < feightTemplateList.length; i++) {
                    this.feightTemplateOptions.push({label: feightTemplateList[i].name, value: feightTemplateList[i].id});
                  }
                });
      },
      getBrandList() {
        fetchBrandList({pageNum: 1, pageSize: 100}).then(response => {
          this.brandOptions = [];
          let brandList = response.data.records;
          for (let i = 0; i < brandList.length; i++) {
            this.brandOptions.push({label: brandList[i].name, value: brandList[i].id});
          }
        });
      },
       getAreaById(id){
        let name=null;
        console.log(JSON.stringify(this.areaOptions))
        for(let i=0;i<this.areaOptions.length;i++){
          for(let j=0;j<this.areaOptions[i].children.length;j++){
            if( this.areaOptions[i].children[j].value!=undefined && this.areaOptions[i].children[j].value===id){
              name=this.areaOptions[i].children[j].label;
              return name;
            }
          }
        }
        return name;
      },
      getCateNameById(id){
        let name=null;
       // console.log(JSON.stringify(this.productCateOptions))
        for(let i=0;i<this.productCateOptions.length;i++){
          for(let j=0;j<this.productCateOptions[i].children.length;j++){
            if(this.productCateOptions[i].children[j].value!=undefined 
            && this.productCateOptions[i].children[j].value===id){
              name=this.productCateOptions[i].children[j].label;
              return name;
            }
          }
        }
        return name;
      },
      handleNext(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('nextStep');
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      handleBrandChange(val) {
        let brandName = '';
        for (let i = 0; i < this.brandOptions.length; i++) {
          if (this.brandOptions[i].value === val) {
            brandName = this.brandOptions[i].label;
            break;
          }
        }
        this.value.brandName = brandName;
      },
      addPmsProductCode(){
        this.value.pmsProductCodes.push({
          id: 0,
          bigsize: "",
          smallsize: "",
          productnum: 0,
          productprices: 0,
          productSn: "",
          productBigSn: ""
        })
      },
      removePmsProductCode(index){
        this.value.pmsProductCodes.splice(index, 1);
      }
    },

  }
</script>

<style scoped>
    .border {
        border-style:solid;
        border-width: 1px;
        border-color: #5a5e66;
    }

    .title{
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #999;
    }
    .title::before,.title::after{
        content: '';
        flex: 1;
        height: 1px;
        background: #ccc;
    }
    .title::before{
        margin-right: 10px;
    }
    .title::after{
        margin-left: 10px;
    }
</style>
